package com.itheiam.consumer.controller;

import com.itheiam.consumer.pojo.Result;
import com.itheima.client.UserClient;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/consumer")
public class Test {
    @Autowired
    UserClient userClient ;
//    @Autowired
//    private RestTemplate restTemplate;
//    @Autowired
//    private DiscoveryClient discoveryClient;
    @GetMapping("/test/{id}")
//    @HystrixCommand(fallbackMethod ="demotion" )
    public Result test(@PathVariable("id")Integer id, HttpServletRequest request){
        String haha = request.getHeader("haha");
        System.out.println(haha);
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        int size = instances.size();
//        Random rd =new Random();
//        int i = rd.nextInt(size);
//        ServiceInstance serviceInstance = instances.get(i);
//        String host = serviceInstance.getHost();
//        int port = serviceInstance.getPort();
        if (id==1){
            throw new RuntimeException("服务器太忙了");
        }

//        String url = String.format("http://user-service/user/test/{id}");
//        String forObject = restTemplate.getForObject(url, String.class, id);
        String forObject = userClient.getUser(id);

        return Result.ok(forObject);

    }
//    public Result demotion(Integer id){
//        return Result.error("访问失败请稍后再试");
//    }
}
